from datetime import datetime
from typing import Optional, List

from pydantic import validator, conint

from exceptions import InvalidParam
from models.administrative_division import AdministrativeDivision
from models.common import RWModel, OID, BaseModel
from utils.dbutil import convert2sort


class BaseSearchModel(BaseModel):
    offset: conint(ge=0, le=2**12) = 0
    size: conint(ge=0, le=50) = 10
    fields: Optional[List[str]] = None
    is_deleted: Optional[bool] = False
    query: Optional[dict]
    sort: Optional[list]
    aggs: Optional[List[str]]

    @validator('offset', "size")
    def no_negative_number(cls, v):
        if v < 0:
            raise InvalidParam("offset/size", "offset/size should be positive number")
        return v

    @validator('sort')
    def parse_sort_value(cls, v):
        return convert2sort(v)


class Institution(RWModel, AdministrativeDivision):
    id: Optional[OID]
    institution_name: Optional[str]
    institution_code: Optional[str]
    alias: Optional[str]
    parent_institution_name: Optional[str]
    establishment_time: Optional[datetime]
    legal_representative: Optional[str]
    institution_type: Optional[str]
    in_kexie: Optional[bool] = False
    # 科协机构类型
    kexie_institution_type: Optional[str]
    # 组织联系人
    contact_person: Optional[str]
    # 组织联系人性别
    contact_gender: Optional[str]
    # 组织联系人职务
    contact_title: Optional[str]
    # 组织联系人电话
    contact_phone: Optional[str]
    administrative_division_code: Optional[str]
    institution_location: Optional[str]
    # 排序要求新增
    served_people_num: Optional[int] = 0


class InstitutionUpdateModel(Institution):
    id: OID


class InstitutionSearchModel(BaseSearchModel):
    name: Optional[str]
    province: Optional[str]
    region: Optional[str]


if __name__ == '__main__':
    update_model = InstitutionUpdateModel()

